package com.mojo.elastic.service.impl;

import com.mojo.elastic.pojo.Log;
import com.mojo.elastic.repository.LogRepository;
import com.mojo.elastic.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/4/25 15:48
 */
@Service
@Slf4j
public class LogServiceImpl implements LogService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private LogRepository logRepository;
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @Override
    public List<Log> findAll() {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.matchPhraseQuery("age", 11));
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQuery query = queryBuilder.withQuery(builder).build();
        return null;
    }

    @Override
    public void boolQuery() {
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        //全文搜索
        bool.must(QueryBuilders.matchQuery("age", 11));
        //段落搜索,精确匹配match_phrase
        bool.should(QueryBuilders.matchPhraseQuery("name", "tom"));
        //过滤查询
        bool.filter(QueryBuilders.matchPhraseQuery("age", 11));
        NativeSearchQueryBuilder nativeBuilder = new NativeSearchQueryBuilder().withQuery(bool);
        SearchHits<Log> hits = elasticsearchRestTemplate.search(nativeBuilder.build(), Log.class);
        List<Log> logs = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        log.info("logs>>>>>>>>>>:{}", log);
    }

    @Override
    public void boosting() {
        //QueryBuilders.boostingQuery()
    }

    @Override
    public void constantScore() {

    }

    @Override
    public void disMax() {

    }

    @Override
    public void functionScore() {

    }

    @Override
    public void aggregationQuery() {

    }
}
